<template>
	<view class="lock-container">
		<!-- 小区信息区域 -->
		<view class="community-info">
			<text class="community-name">{{ communityDisplayName }}</text>
		</view>

		<!-- 门禁选择区域 -->
		<scroll-view scroll-x class="door-selector">
			<view class="door-list">
				<view v-for="door in availableDoors" :key="door.id" class="door-item"
					:class="{ 'active': selectedDoorId === door.id }" @click="selectDoor(door)">
					<text class="door-name">{{ door.name }}</text>
				</view>
			</view>
		</scroll-view>

		<!-- 开门按钮区域 -->
		<view class="unlock-area">
			<view class="unlock-circle" :class="{ 'active': isLoading }">
				<text class="status-text">{{ unlockStatusText }}</text>
				<button @click="handleUnlock" class="unlock-button" :disabled="!canUnlock">
					{{ buttonText }}
				</button>
			</view>
		</view>

		<!-- 开门记录区域（原 doorLock 组件的内容） -->
		<view class="door-log common-card">
			<view class="log-header">
				<text class="log-title">最近开门记录</text>
				<text class="view-all" @click="viewAllLogs">查看全部</text>
			</view>
			<view v-for="record in limitedRecords" :key="record.id" class="log-item">
				<view class="log-left">
					<text class="log-door-name">{{ record.doorName }}</text>
					<text class="log-time">{{ record.time }}</text>
				</view>
				<text class="log-status" :class="{ 'success': record.success }">
					{{ record.success ? '开门成功' : '开门失败' }}
				</text>
			</view>
		</view>

		<!-- 添加弹窗组件 -->
		<uni-popup ref="allLogsPopup" type="bottom">
			<view class="popup-content">
				<view class="popup-header">
					<text class="popup-title">开门记录</text>
					<text class="close-btn" @click="closePopup">关闭</text>
				</view>
				<scroll-view scroll-y class="logs-scroll">
					<view v-for="record in allRecords" :key="record.id" class="log-item">
						<view class="log-left">
							<text class="log-door-name">{{ record.doorName }}</text>
							<text class="log-time">{{ record.time }}</text>
						</view>
						<text class="log-status" :class="{ 'success': record.success }">
							{{ record.success ? '开门成功' : '开门失败' }}
						</text>
					</view>
				</scroll-view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	export default {
		props: {
			communityName: {
				type: String,
				required: true
			},

			communityId: {
				type: String,
				required: true
			},
		},
		data() {
			return {
				selectedDoorId: null,
				isLoading: false,
				availableDoors: [],
				recentRecords: [],
				allRecords: []
			}
		},
		computed: {
			communityDisplayName() {
				return this.communityName;
			},
			selectedDoorName() {
				const door = this.availableDoors.find(d => d.id === this.selectedDoorId);
				return door ? door.name : '';
			},
			unlockStatusText() {
				return this.isLoading ? '开启中' : '一键开门'
			},
			buttonText() {
				return this.selectedDoorName || '请选择门禁'
			},
			canUnlock() {
				return !this.isLoading && this.selectedDoorId
			},
			limitedRecords() {
				return this.recentRecords.slice(0, 5) // 固定显示5条记录
			}
		},
		async created() {
			this.loadRecentRecords();
			await this.loadAvailableDoors();
		},
		onLoad(options) {
			// 接收页面参数
			this.communityId = options.communityId;
			this.communityName = options.communityName;
		},
		methods: {
			// 1. 小区信息相关（暂无特定方法）

			// 2. 门禁选择区域相关
			/**
			 * 加载可用的门禁列表
			 * 从服务器获取门禁数据
			 */
			async loadAvailableDoors() {
				try {
					const response = await uni.request({
						url: 'http://localhost:8500/door/queryAllDoor',
						method: 'GET',
						data: {
							communityId: this.communityId
						}
					});

					if (response.statusCode === 200 && response.data) {
						const {
							code,
							data
						} = response.data;

						if (code === 200 && Array.isArray(data)) {
							this.availableDoors = data;

							if (this.availableDoors.length > 0) {
								this.selectedDoorId = this.availableDoors[0].id;
							}
						} else {
							this.showToast('获取门禁列表失败：无效数据');
						}
					} else {
						this.showToast('获取门禁列表失败：服务器错误');
					}
				} catch (error) {
					console.error('加载门禁列表出错：', error);
					this.showToast('获取门禁列表失败：网络错误');
				}
			},

			/**
			 * 选择门禁
			 */
			selectDoor(door) {
				this.selectedDoorId = door.id;
			},

			// 3. 开门按钮区域相关
			async handleUnlock() {
				if (!this.canUnlock) {
					this.showToast('请先选择要开启的门')
					return
				}

				try {
					this.isLoading = true
					const result = await this.callOpenDoorAPI()

					if (result.success) {
						this.handleUnlockSuccess()
					} else {
						this.handleUnlockError()
					}
				} catch (error) {
					this.handleUnlockError()
				} finally {
					this.isLoading = false
				}
			},

			handleUnlockSuccess() {
				this.addDoorRecord({
					id: Date.now(),
					doorName: this.selectedDoorName,
					time: new Date().toLocaleString(),
					success: true
				})

				this.loadRecentRecords()

				this.showToast('开门成功', 'success')
				this.vibrate()
			},

			handleUnlockError() {
				this.showToast('开门失败，请重试', 'error')
			},

			async callOpenDoorAPI() {
				try {
					// 模拟随机开门结果
					const isSuccess = Math.random() < 0.7; // 70%的概率成功

					// 根据模拟结果发送对应状态的请求
					const response = await uni.request({
						url: 'http://localhost:8500/home/unlock',
						method: 'POST',
						data: {
							communityName: this.communityName,
							doorName: this.selectedDoorName,
							status: isSuccess ? 0 : 1 // 成功发送0，失败发送1
						}
					});

					return {
						success: isSuccess,
						message: isSuccess ? '开门成功' : '开门失败'
					};
				} catch (error) {
					console.error('开门请求出错：', error);
					throw error;
				}
			},

			// 4. 开门记录区域相关
			async loadRecentRecords() {
				try {
					const response = await uni.request({
						url: 'http://localhost:8500/door/queryAllSmartUnlocking',
						method: 'GET',
						data: {
							communityId: this.communityId
						}
					});

					if (response.statusCode === 200 && response.data) {
						const {
							code,
							data
						} = response.data;

						if (code === 200 && Array.isArray(data)) {
							// 只取最新的5条记录
							this.recentRecords = data
								.slice(0, 5)
								.map(record => ({
									id: record.id,
									doorName: record.doorName,
									time: new Date(record.createTime).toLocaleString(),
									success: record.status === 0
								}));
						} else {
							this.showToast('获取开门记录失败：无效数据');
						}
					} else {
						this.showToast('获取开门记录失败：服务器错误');
					}
				} catch (error) {
					console.error('加载开门记录出错：', error);
					this.showToast('获取开门记录失败：网络错误');
				}
			},

			addDoorRecord() {
				this.recentRecords.unshift(record);
				if (this.recentRecords.length > 5) {
					this.recentRecords.pop();
				}
			},

			// 5. 记录弹窗相关
			viewAllLogs() {
				this.loadAllRecords();
				this.$refs.allLogsPopup.open();
			},

			closePopup() {
				this.$refs.allLogsPopup.close();
			},

			async loadAllRecords() {
				try {
					const response = await uni.request({
						url: 'http://localhost:8500/door/queryAllSmartUnlocking',
						method: 'GET',
						data: {
							communityId: this.communityId
						}
					});

					if (response.statusCode === 200 && response.data) {
						const {
							code,
							data
						} = response.data;

						if (code === 200 && Array.isArray(data)) {
							this.allRecords = data.map(record => ({
								id: record.id,
								doorName: record.doorName,
								time: new Date(record.createTime).toLocaleString(),
								success: record.status === 0
							}));
						} else {
							this.showToast('获取完整记录失败：无效数据');
						}
					} else {
						this.showToast('获取完整记录失败：服务器错误');
					}
				} catch (error) {
					console.error('加载完整记录出错：', error);
					this.showToast('获取完整记录失败：网络错误');
				}
			},

			// 通用工具方法
			showToast(title, icon = 'none') {
				uni.showToast({
					title,
					icon
				})
			},

			vibrate() {
				uni.vibrateShort()
			}
		}
	}
</script>

<style lang="scss">
	.lock-container {
		padding: 30rpx;
		min-height: 100vh;
		background-color: #f5f6fa;
	}

	.community-info {
		padding: 30rpx;
		background: #fff;
		border-radius: 16rpx;
		text-align: center;
		margin-bottom: 30rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);

		.community-name {
			font-size: 36rpx;
			font-weight: bold;
			color: #333;
			margin-bottom: 10rpx;
		}

		.building-info {
			font-size: 28rpx;
			color: #666;
		}
	}

	.common-card {
		background: #fff;
		border-radius: 16rpx;
		padding: 20rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
	}

	.unlock-area {
		display: flex;
		justify-content: center;
		align-items: center;
		margin: 60rpx 0;

		.unlock-circle {
			width: 400rpx;
			height: 400rpx;
			border-radius: 50%;
			background: #fff;
			display: flex;
			flex-direction: column;
			justify-content: center;
			align-items: center;
			box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
			transition: all 0.3s ease;

			&.active {
				transform: scale(1.05);
				box-shadow: 0 8rpx 30rpx rgba(76, 175, 80, 0.3);
			}

			.status-text {
				font-size: 36rpx;
				color: #4CAF50;
				font-weight: bold;
				margin-bottom: 20rpx;
			}

			.unlock-button {
				background: transparent;
				border: none;
				color: #666;
				font-size: 28rpx;

				&::after {
					border: none;
				}

				&[disabled] {
					color: #999;
				}
			}
		}
	}

	.door-log {
		background: #fff;
		border-radius: 16rpx;
		padding: 20rpx;

		.log-header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 20rpx;
			border-bottom: 1rpx solid #eee;

			.log-title {
				font-size: 32rpx;
				font-weight: bold;
				color: #333;
			}

			.view-all {
				font-size: 28rpx;
				color: #4CAF50;
			}
		}

		.log-item {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 20rpx;
			border-bottom: 1rpx solid #f5f5f5;

			.log-left {
				display: flex;
				flex-direction: column;

				.log-door-name {
					font-size: 28rpx;
					color: #333;
					margin-bottom: 8rpx;
				}

				.log-time {
					font-size: 24rpx;
					color: #999;
				}
			}

			.log-status {
				font-size: 26rpx;

				&.success {
					color: #4CAF50;
				}

				&.failed {
					color: #F44336;
				}
			}
		}
	}

	@keyframes pulse {
		0% {
			transform: scale(1);
		}

		50% {
			transform: scale(1.05);
		}

		100% {
			transform: scale(1);
		}
	}

	@keyframes rotate {
		from {
			transform: rotate(0deg);
		}

		to {
			transform: rotate(360deg);
		}
	}

	.door-selector {
		background: #fff;
		padding: 20rpx;
		border-radius: 16rpx;
		margin-bottom: 30rpx;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);

		.door-list {
			display: flex;
			white-space: nowrap;

			.door-item {
				display: inline-flex;
				align-items: center;
				justify-content: center;
				padding: 20rpx 40rpx;
				transition: all 0.3s ease;
				min-width: 160rpx;
				height: 80rpx;
				margin: 0 10rpx;
				border-radius: 12rpx;
				background: #f5f5f5;

				&.active {
					background: #4CAF50;

					.door-name {
						color: #fff;
					}
				}

				.door-name {
					font-size: 28rpx;
					color: #333;
					font-weight: 500;
				}
			}
		}
	}

	.unlock-button {
		&[disabled] {
			opacity: 0.7;
			background: #f5f5f5;
		}
	}

	.popup-content {
		background-color: #fff;
		border-radius: 24rpx 24rpx 0 0;
		padding: 30rpx;
		max-height: 70vh;

		.popup-header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding-bottom: 20rpx;
			border-bottom: 1rpx solid #eee;
			margin-bottom: 20rpx;

			.popup-title {
				font-size: 32rpx;
				font-weight: bold;
				color: #333;
			}

			.close-btn {
				font-size: 28rpx;
				color: #666;
				padding: 10rpx;
			}
		}

		.logs-scroll {
			max-height: calc(70vh - 100rpx);
		}
	}
</style>